# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

NACL_SDK_ROOT ?= $(abspath $(CURDIR)/../..)
include $(NACL_SDK_ROOT)/tools/common.mk

TARGET = python
LIBS = python2.7 readline ncurses nacl_spawn ppapi_simple tar nacl_io \
       ppapi_cpp ppapi ssl crypto bz2
NACL_LDFLAGS += $(NACL_CLI_MAIN_LIB)
PNACL_LDFLAGS += $(NACL_CLI_MAIN_LIB)
ifeq ($(TOOLCHAIN),glibc)
LIBS += util dl
NACL_LDFLAGS += -Wl,-export-dynamic
else
LIBS += glibc-compat z
endif
SOURCES = python.c
INC_PATHS = $(NACLPORTS_INCLUDE)/python2.7
INSTALL_DIR = $(NACL_PACKAGES_PUBLISH)/python/$(TOOLCHAIN)

ifeq ($(TOOLCHAIN),pnacl)
EXEEXT=.pexe
else
EXEEXT=.nexe
endif

ifneq ($(TOOLCHAIN),pnacl)
# We want the nmf to contain all the .nexe we have previously
# built as well as the one currently being built, so we modify
# the list of executables that we pass to create_nmf.
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_x86_64$(EXEEXT))
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_x86_32$(EXEEXT))
EXECUTABLES += $(wildcard $(OUTDIR)/$(TARGET)_arm$(EXEEXT))
endif

# Build rules generated by macros from common.mk:

$(foreach src,$(SOURCES),$(eval $(call COMPILE_RULE,$(src),$(CFLAGS))))

ifeq ($(CONFIG),Release)
$(eval $(call LINK_RULE,$(TARGET)_unstripped,$(SOURCES),$(LIBS),$(DEPS)))
$(eval $(call STRIP_RULE,$(TARGET),$(TARGET)_unstripped))
else
$(eval $(call LINK_RULE,$(TARGET),$(SOURCES),$(LIBS),$(DEPS)))
endif

$(eval $(call NMF_RULE,$(TARGET),))

ASSETS = lib/python2.7
ifeq ($(TOOLCHAIN),glibc)
ASSETS += lib/libz.so.1 lib/libreadline.so lib/libncurses.so.5
endif

CHROMEAPPS = $(NACL_SRC)/third_party/libapps/
LIB_DOT = $(CHROMEAPPS)/libdot
NASSH = $(CHROMEAPPS)/nassh

install:
	mkdir -p $(INSTALL_DIR)
	../../build_tools/template_expand.py manifest.json version=$(NACLPORTS_REVISION) > $(INSTALL_DIR)/manifest.json
	tar -h -c -C ${NACL_PREFIX} -f $(INSTALL_DIR)/pydata_$(NACL_ARCH).tar --exclude lib/python2.7/site-packages ${ASSETS}
	LIBDOT_SEARCH_PATH=$(CHROMEAPPS) $(LIB_DOT)/bin/concat.sh -i $(NASSH)/concat/nassh_deps.concat -o $(INSTALL_DIR)/hterm.concat.js
	cp $(OUTDIR)/python*$(EXEEXT) $(INSTALL_DIR)
	rm -f $(INSTALL_DIR)/*_unstripped_*$(EXEEXT)
	cp $(OUTDIR)/python.nmf $(INSTALL_DIR)
	cp index.html $(INSTALL_DIR)
	cp python.js $(INSTALL_DIR)
	cp ../../build_tools/naclterm.js $(INSTALL_DIR)
	cp ../../build_tools/pipeserver.js $(INSTALL_DIR)
	cp ../../build_tools/naclprocess.js $(INSTALL_DIR)
	cp background.js $(INSTALL_DIR)
	cp icon_16.png $(INSTALL_DIR)
	cp icon_48.png $(INSTALL_DIR)
	cp icon_128.png $(INSTALL_DIR)
ifeq ($(TOOLCHAIN),pnacl)
	sed -i.bak 's/x-nacl/x-pnacl/g' $(INSTALL_DIR)/naclprocess.js
endif
ifeq ($(TOOLCHAIN),glibc)
	cp -r $(OUTDIR)/lib* $(INSTALL_DIR)
endif
	cd $(INSTALL_DIR) && rm -f python.zip && zip -r python.zip .
